<template>
  <div>
    <el-card style="height: 80px">
      <div class="box-card-div">

        <el-form :inline="true" :model="order" ref="ruleForm" class="demo-form-inline">
          <el-form-item label="订单编号" prop="orderId">
            <el-input
              style="width: 200px;"
              size="small"
              v-model="order.orderId"
              placeholder="请输入订单编号"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="入住时间"  prop="inTime" style="margin-left: 50px">
            <el-date-picker
              style="width: 250px"
              v-model="order.inTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              size="small"
              clearable
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>&nbsp;&nbsp;_
          <el-form-item label="离开时间" prop="outTime" style="margin-left: 5px">
            <el-date-picker
              style="width: 250px"
              v-model="order.outTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              size="small"
              clearable
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

          <el-form-item style="margin-left: 20px">
            <el-button type="success" plain size="small" @click="onSearch">查询</el-button>
            &nbsp;&nbsp;&nbsp;&nbsp;
            <el-button type="warning" plain size="small" @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>
          <br>
        </el-form>
      </div>
    </el-card>

    <div>
      <br>
      <el-button type="primary" plain size="small" @click="handleAddDialog = true">新增</el-button>
      <el-button type="danger" plain size="small" @click="handleDeleteAll">批量删除</el-button>
      <br>
    </div>

    <!--新增的弹框-->
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      style="margin-left: 300px; width: 1400px"
      :visible.sync="handleAddDialog"
    >
      <el-form
        :model="editOrder"
        label-width="120px"
        :rules="rules"
        ref="editOrder"
      >
        <!-- 订单编号 -->
        <el-form-item label="订单编号" prop="orderId">
          <el-input
            v-model="editOrder.orderId"
            placeholder="请输入订单编号"
            clearable
            :style="{width: '100%'}"
          ></el-input>
        </el-form-item>

        <!-- 预订人名称 -->
        <el-form-item label="预订人" prop="userId">
          <el-input
            v-model="editOrder.userId"
            placeholder="请输入预订人名称"
            clearable
            :style="{width: '100%'}"
          ></el-input>
        </el-form-item>



        <el-form-item label="房型类型" prop="typeId">
          <el-select v-model="editOrder.typeId" placeholder="请选择房型类型">
            <el-option label="双人间" :value="1"></el-option>
            <el-option label="单间" :value="2"></el-option>
            <el-option label="大床独立卫浴" :value="3"></el-option>
            <el-option label="一室一厅一卫" :value="4"></el-option>
            <el-option label="两室一厅一卫" :value="5"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="入住时间" prop="inTime">
          <el-date-picker v-model="editOrder.inTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间"></el-date-picker>

        </el-form-item>
        <el-form-item label="离开时间" prop="outTime">
          <el-date-picker v-model="editOrder.outTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间"></el-date-picker>
        </el-form-item>

        <el-form-item label="入住天数" prop="days">
          <el-input v-model="editOrder.days"></el-input>
        </el-form-item>

        <el-form-item label="订单状态" prop="status">
          <el-select v-model="editOrder.status" placeholder="请选择订单状态">
            <el-option label="待付款" value="待付款"></el-option>
            <el-option label="已付款" value="已付款"></el-option>
            <el-option label="已完成" value="已完成"></el-option>
            <el-option label="已入住" value="已入住"></el-option>
            <el-option label="已退房" value="已退房"></el-option>
          </el-select>
        </el-form-item>

        <!-- action为空，表示不使用默认的上传行为，需要通过http-request属性自定义上传方法-->
        <el-form-item label="图片" prop="img">
          <el-upload
            class="upload-img"
            action=""
            auto-upload
            :http-request="handleUpload"
            :show-file-list="false"
            drag
            multiple>
            <i class="el-icon-upload"></i>
            <div class="el-icon-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <img
              v-if="editOrder.img"
              :src="getFullImgUrl(editOrder.img)"
              style="max-width: 120px; margin-top: 10px; display: block;"
            />
          </el-upload>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('editOrder')" size="small">取 消</el-button>
        <el-button type="primary" @click="submitForm('editOrder')" size="small">确 定</el-button>
      </div>
    </el-dialog>


    <el-table
      :data="tableData"
      stripe
      max-height="700"
      @selection-change="handleChoiceChange"
      style="width: 100%">
      <!-- 多选框 -->
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <!-- 序号 -->
      <el-table-column
        label="序号"
        prop="id"
        width="100">
      </el-table-column>
      <!-- 图片 -->
      <el-table-column
        label="图片"
        prop="img"
        width="80">
        <template slot-scope="scope">
          <img :src="baseUrl + scope.row.img" alt="Image" style="max-width: 60px; max-height: 60px;">
        </template>
      </el-table-column>
      <!-- 订单编号 -->
      <el-table-column
        prop="orderId"
        width="100"
        label="订单编号">
      </el-table-column>
      <el-table-column
        prop="userId"
        width="100"
        label="预订人">
      </el-table-column>
      <!-- 客房 -->
      <el-table-column label="客房">
        <template slot-scope="scope">
          {{ getRoomType(scope.row.typeId) }}
        </template>
      </el-table-column>
      <!-- 预订时间 -->
<!--      <el-table-column-->
<!--        prop="time"-->
<!--        label="预订时间">-->
<!--      </el-table-column>-->
      <!-- 入住时间 -->
      <el-table-column
        prop="inTime"
        label="入住时间"
        width="100"
      >
      </el-table-column>
      <!-- 离开时间 -->
      <el-table-column
        prop="outTime"
        label="离开时间">
      </el-table-column>
      <!-- 入住天数 -->
      <el-table-column
        prop="days"
        width="100"
        label="入住天数">
      </el-table-column>
      <!-- 订单状态 -->
      <el-table-column
        prop="status"
        width="170"
        label="订单状态">
      </el-table-column>
      <el-table-column
        prop="yuYueOrder.testId"
        width="150"
        label="联查测试">
      </el-table-column>
      <!-- 操作 -->
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div style="display: flex; align-items: center; margin-top: 30px; margin-left: 400px;">
      <el-pagination
        background
        @size-change="handleSizeChange"
        :page-sizes="[5, 7, 10]"
        @current-change="handleCurrentChange"
        :current-page="order.pageNum"
        :page-size="order.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
      <el-button style="margin-left: 10px" size="small" type="primary" plain @click="toPage">跳转</el-button>
    </div>


  </div>
</template>

<script>

import {
  queryAllSysOrderPage, SysOrderImgUpload, SysOrderImgUpload2,
  ZfSysOrderAdd,
  ZfSysOrderDelete,
  ZfSysOrderDeleteAll,
  ZfSysOrderUpdate
} from '@/api/zf/zf-sys-order'

export default {
  name: 'SysOrderManage',
  data() {
    return {
      title: '添加用户',
      tableData: [],
      handleAddDialog: false,
      handleChoice: [],
      baseUrl: 'https://wanghao1234.oss-cn-hangzhou.aliyuncs.com/g8hms/',
      order: {
        pageSize: 7,
        pageNum: 1,
      },
      editOrder: {
        orderId: '',
        userId: '',
        yuYueOrder: {
          testId: ''
        },
        hotelId: '',
        typeId: '',
        inTime: '',
        outTime: '',
        days: '',
        price: '',
        status: '',
        img: ''
      },
      rules: {
        orderNum: [{ required: true, message: '请输入订单编号', trigger: 'blur' }],
        id: [{ required: true, message: '请输入用户ID', trigger: 'blur' }],
        yongHuName: [{ required: true, message: '请输入用户姓名', trigger: 'blur' }],
        status: [{ required: true, message: '请选择订单状态', trigger: 'change' }],
        creatDate: [{ required: true, message: '请选择预约时间', trigger: 'change' }]
      },
      total: 0,
      loading: false
    }
  },
  methods: {
    // 查询全部订单
    queryAllSysOrder() {
      this.loading = true;
      queryAllSysOrderPage(this.order).then(ret => {
        console.log(ret.data.list); // 检查返回的数据结构
        this.tableData = ret.data.list;
        this.total = ret.data.total;
      });
    },
    getRoomType(typeId) {
      switch (typeId) {
        case 1:
          return '双人间';
        case 2:
          return '单间';
        case 3:
          return '大床独立卫浴';
        case 4:
          return '一室一厅一卫';
        case 5:
          return '两室一厅一卫';
        default:
          return '未知';
      }
    },
    // days() {
    //   const inTime = parseInt(this.editOrder.inTime);
    //   const outTime = parseInt(this.editOrder.outTime);
    //   const days = Math.ceil((outTime.getTime() - inTime.getTime()) / (24 * 60 * 60 * 1000));
    //   this.editOrder.days = days;
    //   console.log(days);
    // },
    handleSizeChange(size) {
      console.log('每页${size}条');
      this.order.pageSize = size;
      this.queryAllSysOrder();
    },
    handleCurrentChange(currentPage) {
      this.order.pageNum = currentPage;
      this.queryAllSysOrder();
    },
    toPage() {
      this.queryAllSysOrder();
    },
    onSearch() {
      this.queryAllSysOrder();
    },
    handleEdit(index, row) {
      this.title = "修改用户";
      this.editOrder = row;
      this.handleAddDialog = true;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.title === "添加用户") {
            ZfSysOrderAdd(this.editOrder).then(ret => {
              if (ret.code === 20000) {
                this.$message({
                  type: 'success',
                  message: '添加成功!',
                  duration: 1000
                });
                this.queryAllSysOrder()
                this.editOrder = {};
                this.$refs[formName].resetFields();
              }
            })
          } else {
            ZfSysOrderUpdate(this.editOrder)
              .then(ret => {
                if (ret.code === 20000) {
                  this.$message({
                    type: 'success',
                    message: '更新成功!',
                    duration: 1000
                  });
                  this.$refs[formName].resetFields();
                  this.resetForm(formName);
                  this.queryAllSysOrder()
                }
              })
          }
          this.handleAddDialog = false;
        } else {
          this.$message({
            type: 'error',
            message: '请检查是否输入正确!'
          });
          return false;
        }
      });
    },

    handleDelete(index, row) {
      this.$confirm('此操作将永久删除' + '"' + row.orderId + '：' + row.userId + '"' + '该数据, 是否继续?', '删除用户!', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        ZfSysOrderDelete(row.id).then(ret => {
          if (ret.code === 20000) {
            // 弹框
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.queryAllSysOrder();
          } else {
            this.$message({
              type: 'error',
              message: '删除失败，请稍后重试！'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleChoiceChange(val) {
      this.handleChoice = val.map(order => order.id);
      console.log(this.handleChoice);
    },
    handleDeleteAll() {
      if (this.handleChoice.length === 0) {
        this.$message({
          type: 'warning',
          message: '请选择要删除的数据!'
        });
        return;
      }
      this.$confirm('此操作将永久删除['+this.handleChoice+']数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        ZfSysOrderDeleteAll(this.handleChoice).then(ret => {
          if (ret.code === 20000) {
            // 弹框
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.queryAllSysOrder();
          }else{
            this.$message({
              type: 'error',
              message:'删除失败，请稍后重试！'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    getFullImgUrl(imgPath) {
      return this.baseUrl + imgPath;
    },
    handleUpload({ file }){
      if(!this.editOrder.orderId){
        this.$message({
          type: 'error',
          message: '请先填写订单信息！'
        });
        return;
      }
      const formData = new FormData();
      formData.append('file', file);
      formData.append('orderId', this.editOrder.orderId);

      // 根据当前操作决定调用接口
      const uploadApi = this.title === "添加用户" ? SysOrderImgUpload2 : SysOrderImgUpload;
        uploadApi(formData).then(ret => {
          if (ret.code === 20000) {
            this.editOrder.img = ret.data;
            this.$message({
              type: 'success',
              message: '上传成功！'
            });
            this.queryAllSysOrder();
          }
        }).catch(err => {
          console.log(err);
          this.$message({ type: 'error', message: '上传失败，请稍后重试！' });
        });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.handleAddDialog = false;
      this.editOrder = {
        status: '已解决',
        img: ''
      };
      this.title = "添加用户";
      this.queryAllSysOrder();
    },
  },
  created() {
    this.queryAllSysOrder();
  }
}
</script>

<style scoped lang="scss">

</style>
